package com.qjdchina.sku.boss.web.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.qjdchina.sku.model.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.qjdchina.common.web.util.RestBody;
import com.qjdchina.commons.enums.IsDeleted;
import com.qjdchina.commons.result.Result;
import com.qjdchina.sku.biz.BrandManager;
import com.qjdchina.sku.biz.CategoryBrandManager;
import com.qjdchina.sku.biz.CategoryManager;
import com.qjdchina.sku.biz.RelProductSkuAttributeManager;
import com.qjdchina.sku.biz.RoleCategoryManager;
import com.qjdchina.sku.biz.RoleManager;
import com.qjdchina.sku.biz.SkuItemAttributeManager;
import com.qjdchina.sku.biz.SkuItemManager;
import com.qjdchina.sku.biz.SkuProductManager;
import com.qjdchina.sku.cache.CategoryCache;
import com.qjdchina.sku.consts.WebConsts;
import com.qjdchina.sku.model.Category;
import com.qjdchina.sku.model.CategoryBrand;
import com.qjdchina.sku.model.RelProductSkuAttribute;
import com.qjdchina.sku.model.Role;
import com.qjdchina.sku.model.query.CategoryQueryVO;
import com.qjdchina.sku.service.enums.SkuResultCode;

/**
 * 
 * @author shenpingfeng 2017年2月13日
 */
@Controller
@RequestMapping(value = "category")
public class CategoryController {

	@Autowired
	private CategoryManager categoryManager;
	@Autowired
	private SkuItemManager skuItemManager;
	@Autowired
	private SkuItemAttributeManager skuItemAttributeManager;
	@Autowired
	private RoleCategoryManager roleCategoryManager;
	@Autowired
	private RoleManager roleManager;
	@Autowired
	private RelProductSkuAttributeManager relProductSkuAttributeManager;
	@Autowired
	private SkuProductManager skuProductManager;
	@Autowired
	private CategoryBrandManager categoryBrandManager;
	@Autowired
	private BrandManager brandManager;

	/**
	 * 获取所有一级品类 shenpingfeng 2017年2月16日
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getRootCategory", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<Category>> getRootCategory(HttpSession session) {

		Result<List<Category>> allRootCategory = categoryManager.getAllRootCategory();
		if (!allRootCategory.isSuccess()) {
			return new RestBody<List<Category>>(allRootCategory.getResultCode());
		}

		return new RestBody<List<Category>>(SkuResultCode.SUCCESS, allRootCategory.getDataModel());
	}

	/**
	 * 根据父品类查询所有的子品类
	 * 
	 * @param parentId
	 * @return
	 */
	@RequestMapping(value = "getChildCategorys", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<Category>> getChildCategory(
			@RequestParam(value = "parentId", required = true) Integer parentId, HttpSession session) {

		Result<List<Category>> allRootCategory = categoryManager.getChildCategorys(parentId);
		if (!allRootCategory.isSuccess()) {
			return new RestBody<List<Category>>(allRootCategory.getResultCode());
		}

		return new RestBody<List<Category>>(SkuResultCode.SUCCESS, allRootCategory.getDataModel());
	}

	/**
	 * 创建 shenpingfeng 2017年2月14日
	 * 
	 * @param category
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<Integer> create(Category category, HttpSession session) {
		String userName = (String) session.getAttribute(WebConsts.USER_NAME);
		category.setOperateId(userName);
		Result<String> result = categoryManager.createCategory(category);
		if (!result.isSuccess()) {
			return new RestBody<Integer>(result.getCode(), result.getMessage());
		}
		CategoryQueryVO categoryQueryVO = new CategoryQueryVO();
		categoryQueryVO.setCode(result.getDataModel());
		Result<Category> cResult = categoryManager.getCategoryWhereStatement(categoryQueryVO);
		if (!cResult.isSuccess()) {
			return new RestBody<Integer>(cResult.getCode(), cResult.getMessage());
		}

		Category cate = cResult.getDataModel();
		// 获取所有角色 角色绑定品类
		Result<List<Role>> resultRole = roleManager.getAllRole();
		if (resultRole.isSuccess()) {
			List<Role> roles = resultRole.getDataModel();
			for (Role role : roles) {
				RoleCategoryVO roleCategoryVO = new RoleCategoryVO();
				roleCategoryVO.setSkuRoleId(role.getId());
				roleCategoryVO.setSkuCategoryId(cate.getId());
				Result<String> resultCreate = roleCategoryManager.create(roleCategoryVO);
				if (!resultCreate.isSuccess()) {
					return new RestBody<>(resultCreate.getCode(), resultCreate.getMessage());
				}
			}
		}
		CategoryCache.destroy();

		return new RestBody<Integer>(SkuResultCode.SUCCESS, cate.getId());
	}

	/**
	 * 更新品类 shenpingfeng 2017年1月12日
	 * 
	 * @param category
	 * @return
	 */
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> update(Category category) {
		Result<String> resultUpdate = categoryManager.update(category);
		if (!resultUpdate.isSuccess()) {
			return new RestBody<>(resultUpdate.getCode(), resultUpdate.getMessage());
		}
		CategoryCache.destroy();
		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 添加品牌 shenpingfeng 2017年2月13日
	 * 
	 * @param skuCategoryId
	 *            skuBrandIds
	 * @return
	 */
	@RequestMapping(value = "addBrand", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> addBrand(@RequestParam(value = "skuCategoryId", required = true) Integer skuCategoryId,
			String skuBrandIds) {
		if(StringUtils.isBlank(skuBrandIds)){
			return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		String[] skuBrandIdList = skuBrandIds.split(",");
		if (skuCategoryId == null || skuBrandIds == null || skuBrandIdList.length == 0) {
			return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		for (String skuBrandId : skuBrandIdList) {
			CategoryBrand categoryBrand = new CategoryBrand();
			categoryBrand.setSkuCategoryId(skuCategoryId);
			categoryBrand.setSkuBrandId(Integer.parseInt(skuBrandId));
			Result<String> result = categoryManager.createCategoryBrand(categoryBrand);
			if (!result.isSuccess()) {
				return new RestBody<String>(result.getCode(), result.getMessage());
			}
		}
		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 删除品牌 shenpingfeng 2017年2月13日
	 * 
	 * @param categoryBrands
	 * @return
	 */	
	@RequestMapping(value = "deleteBrand", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> deleteBrand(String categoryBrands) {
		if (StringUtils.isBlank(categoryBrands)) {
			return new RestBody<String>(SkuResultCode.PARAMETER_NOT_EMPTY);
		}
		List<CategoryBrand> categoryBrandsList = JSON.parseArray(categoryBrands, CategoryBrand.class);
		for (CategoryBrand categoryBrand : categoryBrandsList) {
			Integer skuBrandId = categoryBrand.getSkuBrandId();
			Integer skuCategoryId = categoryBrand.getSkuCategoryId();
			// 判断该品类品牌下是否有部品存在，如果存在，不能删除关联关系
			Result<List<SkuProductVO>> result = skuProductManager.findProductBySkuCategoryIdAndSkuBrandId(skuCategoryId,skuBrandId);
			if (result.isSuccess()) {
				return new RestBody<String>(SkuResultCode.BRAND_PRODUCT_RELATION);
			}
		}

		// 删除
		for (CategoryBrand categoryBrand : categoryBrandsList) {
			Integer skuBrandId = categoryBrand.getSkuBrandId();
			Integer skuCategoryId = categoryBrand.getSkuCategoryId();
			String isDeleted = categoryBrand.getIsDeleted();
			if(StringUtils.isNotBlank(isDeleted)&&isDeleted.equals(IsDeleted.YES.getValue())){
				//更新
				Result<CategoryBrand> result = categoryBrandManager.getCategoryBrandBySkuBrandIdAndSkuCategoryId(skuBrandId,skuCategoryId);
				if (!result.isSuccess()) {
					return new RestBody<>(result.getCode(), result.getMessage());
				}
				CategoryBrand cBrand = result.getDataModel();
				Result<String> uResult = categoryBrandManager.delete(cBrand);
				if (!uResult.isSuccess()) {
					return new RestBody<String>(uResult.getCode(), uResult.getMessage());
				}
			}else {
				categoryBrand.setSkuCategoryId(skuCategoryId);
				categoryBrand.setSkuBrandId(skuBrandId);
				Result<String> result = categoryManager.createCategoryBrand(categoryBrand);
				if (!result.isSuccess()) {
					return new RestBody<String>(result.getCode(), result.getMessage());
				}
			}
			
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 创建表头 shenpingfeng 2017年2月13日
	 * 
	 * @param skuItemVO
	 * @param attributeValues
	 * @return
	 */
	@RequestMapping(value = "createItem", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> createItem(SkuItemVO skuItemVO, String[] attributeValues) {
		Result<String> result = skuItemManager.create(skuItemVO);
		if (!result.isSuccess()) {
			return new RestBody<String>(result.getCode(), result.getMessage());
		}
		String code = result.getDataModel();
		Result<SkuItemVO> sResult = skuItemManager.getSkuItemByCode(code);
		if (!sResult.isSuccess()) {
			return new RestBody<String>(sResult.getCode(), sResult.getMessage());
		}
		SkuItemVO sItemVO = sResult.getDataModel();
		// 校验表头属性是否存在
		if (attributeValues != null && attributeValues.length > 0) {
			for (int i = 0; i < attributeValues.length; i++) {
				String value = attributeValues[i];
				Result<SkuItemAttributeVO> aResult = skuItemAttributeManager
						.getSkuItemAttributeBySkuItemIdAndValue(sItemVO.getId(), value);
				if (aResult.isSuccess()) {
					return new RestBody<String>(SkuResultCode.SKU_ITEM_ATTRIBUTE_EXIST);
				}
				for (int j = i + 1; j < attributeValues.length; j++) {
					String attrValue = attributeValues[j];
					if (value.equals(attrValue)) {
						return new RestBody<String>(SkuResultCode.SKU_ITEM_ATTRIBUTE_REPEAT);
					}
				}
			}
			// 创建表头属性值
			for (String itemAttribute : attributeValues) {
				SkuItemAttributeVO skuItemAttributeVO = new SkuItemAttributeVO();
				skuItemAttributeVO.setValue(itemAttribute);
				skuItemAttributeVO.setSkuItemId(sItemVO.getId());
				Result<String> cResult = skuItemAttributeManager.create(skuItemAttributeVO);
				if (!cResult.isSuccess()) {
					return new RestBody<String>(cResult.getCode(), cResult.getMessage());
				}
			}
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 更新表头 shenpingfeng 2017年2月14日
	 * 
	 * @param skuItemVO
	 * @return
	 */
	@RequestMapping(value = "updateItem", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> updateItem(SkuItemVO skuItemVO, String skuItemAttributes) {		
		// 更新属性
		if (StringUtils.isNotBlank(skuItemAttributes)) {
			List<SkuItemAttributeVO> skuItemAttributeVOs = JSON.parseArray(skuItemAttributes, SkuItemAttributeVO.class);
			List<SkuItemAttributeVO> addSkuItemAttributeVOs = new ArrayList<>();
			List<SkuItemAttributeVO> updateSkuItemAttributeVOs = new ArrayList<>();

			if (skuItemAttributeVOs != null && skuItemAttributeVOs.size() > 0) {
				for (SkuItemAttributeVO skuItemAttributeVO : skuItemAttributeVOs) {
					Integer id = skuItemAttributeVO.getId();
					if (id == null) {
						addSkuItemAttributeVOs.add(skuItemAttributeVO);
					} else {
						updateSkuItemAttributeVOs.add(skuItemAttributeVO);
					}
				}
				// 校验新增属性
				for (int i = 0; i < addSkuItemAttributeVOs.size(); i++) {
					String value = addSkuItemAttributeVOs.get(i).getValue();
					Result<SkuItemAttributeVO> aResult = skuItemAttributeManager
							.getSkuItemAttributeBySkuItemIdAndValue(skuItemVO.getId(), value);
					if (aResult.isSuccess()) {
						return new RestBody<String>(SkuResultCode.SKU_ITEM_ATTRIBUTE_EXIST);
					}
					for (int j = i + 1; j < addSkuItemAttributeVOs.size(); j++) {
						String attrValue = addSkuItemAttributeVOs.get(j).getValue();
						if (value.equals(attrValue)) {
							return new RestBody<String>(SkuResultCode.SKU_ITEM_ATTRIBUTE_REPEAT);
						}
					}
				}

				// 校验更新属性
				// 判断属性是否跟部品关联，如果有关联，不能更新
				for (SkuItemAttributeVO skuItemAttributeVO : updateSkuItemAttributeVOs) {
					Result<List<RelProductSkuAttribute>> rResult = relProductSkuAttributeManager
							.getRelProductSkuAttributeBySkuItemIdAndValue(skuItemVO.getId(),
									skuItemAttributeVO.getValue());
					if (rResult.isSuccess()) {
						return new RestBody<>(SkuResultCode.SKU_ITEM_ATTRIBUTE_PRODUCT_RELATION);
					}
				}
				
				// 创建表头属性值
				for (SkuItemAttributeVO skuItemAttributeVO : addSkuItemAttributeVOs) {
					skuItemAttributeVO.setSkuItemId(skuItemVO.getId());
					Result<String> cResult = skuItemAttributeManager.create(skuItemAttributeVO);
					if (!cResult.isSuccess()) {
						return new RestBody<String>(cResult.getCode(), cResult.getMessage());
					}
				}
				// 更新表头属性
				for (SkuItemAttributeVO skuItemAttributeVO : updateSkuItemAttributeVOs) {
					Result<String> uResult = skuItemAttributeManager.update(skuItemAttributeVO);
					if (!uResult.isSuccess()) {
						return new RestBody<String>(uResult.getCode(), uResult.getMessage());
					}
				}	
			}
		}
		
		Result<String> result = skuItemManager.update(skuItemVO);
		if (!result.isSuccess()) {
			return new RestBody<String>(result.getCode(), result.getMessage());
		}

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 删除表头 TODO shenpingfeng 2017年2月13日
	 * 
	 * @param categoryId
	 * @param skuItemId
	 * @return
	 */
	@RequestMapping(value = "deleteItem", method = RequestMethod.POST)
	@ResponseBody
	public RestBody<String> deleteItem(Integer categoryId, Integer skuItemId) {

		return new RestBody<String>(SkuResultCode.SUCCESS);
	}

	/**
	 * 获取品类关联品牌 shenpingfeng 2017年2月21日
	 * 
	 * @param categoryId
	 * @return
	 */
	@RequestMapping(value = "getBrands", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<BrandVO>> getBrands(Integer categoryId) {
		Result<List<BrandVO>> result = brandManager.getBrandByCategory(categoryId);
		if (!result.isSuccess()) {
			return new RestBody<List<BrandVO>>(result.getCode(), result.getMessage());
		}
		return new RestBody<List<BrandVO>>(SkuResultCode.SUCCESS, result.getDataModel());
	}
	
	/**
	 * 获取表头及属性
	 * shenpingfeng
	 * 2017年2月23日
	 * @param categoryId
	 * @return
	 */
	@RequestMapping(value = "getSkuItems", method = RequestMethod.GET)
	@ResponseBody
	public RestBody<List<SkuItemBasicVO>> getSkuItemByCategoryId(Integer categoryId) {
		Result<Map<String, Object>> result = skuItemManager.getSkuByCategoryId(categoryId);
		if (!result.isSuccess() && !SkuResultCode.DATA_NOT_EXIST.getCode().equals(result.getCode())) {
			return new RestBody<List<SkuItemBasicVO>>(result.getCode(), result.getMessage());
		}
		List<SkuItemBasicVO> skuItemBasicVOs = null;
		if (result.getDataModel() != null) {
			skuItemBasicVOs = (List<SkuItemBasicVO>) result.getDataModel().get("skuItemBasicVOs");
		}
		return new RestBody<List<SkuItemBasicVO>>(SkuResultCode.SUCCESS, skuItemBasicVOs);
	}

}
